package com.zrgj.front.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zrgj.common.ali.AliyunSmsUtils;
import com.zrgj.common.response.BaseResponse;
import com.zrgj.common.response.StatusCodeEnum;
import com.zrgj.domain.User;
import com.zrgj.manager.service.IUserService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private IUserService userService;

    private final AliyunSmsUtils aliyunSmsUtils = new AliyunSmsUtils() ;


    @PostMapping("/login")
    public BaseResponse login(@RequestBody User user, HttpServletResponse response) {
        User login = userService.login(user);
        if (login != null) {
            Cookie cookie = new Cookie("USER_NAME",login.getUserName());
            cookie.setMaxAge(1800);
            cookie.setPath("/");
            response.addCookie(cookie);

            return new BaseResponse<>(StatusCodeEnum.SUCCESS);
        }

        return new BaseResponse<>(StatusCodeEnum.LOGIN_ERROR);
    }

    @PostMapping("/logout")
    public BaseResponse logout(String cookieName, HttpServletResponse response){

        Cookie cookies = new Cookie(cookieName,null);
        cookies.setMaxAge(0);
        cookies.setPath("/");
        response.addCookie(cookies);
        return new BaseResponse(StatusCodeEnum.SUCCESS,"index");
    }

    @PostMapping("/checkName")
    public BaseResponse checkName(String username) {
        User user = userService.findByName(username);
        if (user != null){
            return new BaseResponse(StatusCodeEnum.NO_CONTENT,true);
        }

        return new BaseResponse(StatusCodeEnum.NO_CONTENT, false);
    }

    @PostMapping("/register")
    public BaseResponse register(@RequestBody User user){
        userService.register(user);

        return new BaseResponse(StatusCodeEnum.SUCCESS,"loginUI");
    }

    @PostMapping("/getCode")
    public BaseResponse getCode(String phone) throws Exception{
        Integer code = aliyunSmsUtils.getNewcode();
//        aliyunSmsUtils.sendSms(phone,code.toString());

        return new BaseResponse(StatusCodeEnum.SUCCESS,code);
    }

}
